package com.zff.web.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.zff.web.constants.Constants;
import com.zff.web.dao.WxTextMapper;
import com.zff.web.outsideInter.TuLingApiService;
import com.zff.web.po.WxTextPo;
import com.zff.web.service.WxTextService;
import com.zff.wechat.util.GDUtil;

@Service
public class WxTextServiceImpl implements WxTextService {

	private static Logger LOG = Logger.getLogger(WxTextServiceImpl.class);
	
	@Autowired
	private WxTextMapper wxTextDao;
	
	@Autowired
	private TuLingApiService tuLingApiService;
	
	public WxTextPo fetchAnswerByGreet(String ttGreet) throws Exception {
		System.out.println(ttGreet);
		List<WxTextPo> fetchAnswerByGreet = wxTextDao.fetchAnswerByGreet(ttGreet);
		int randomIndex = GDUtil.randomNum(fetchAnswerByGreet.size());
		
		if (Constants.zero == fetchAnswerByGreet.size()) {
			String tulingSearchResult = tuLingApiService.getTulingResult(ttGreet);
			// 将接口返回的json转成map
//			Map<String, Object> resultMap = JSON.parseObject(tulingSearchResult, Map.class);
			// 将接口返回的json转成JSONObject
			JSONObject jsonObject = JSONObject.parseObject(tulingSearchResult);
			String text = jsonObject.getString("text");
			WxTextPo newWxText = new WxTextPo();
			if (jsonObject.containsKey("url")) {
				LOG.info("返回json存在url信息");
				String url = jsonObject.getString("url");
				saveWxText(ttGreet,(text+("<a href='"+url+"'>打开页面</a>")));
				newWxText.setTtAnswer((text+("<a href='"+url+"'>打开页面</a>")));
			}else{
				LOG.info("返回json无url信息");
				saveWxText(ttGreet,text);
				newWxText.setTtAnswer(text);
			}
			return newWxText;
		}
		return fetchAnswerByGreet.get(randomIndex);
	}

	@Transactional
	@Override
	public int saveWxText(String greet, String answer) throws Exception {
		WxTextPo newWxTextPo = new WxTextPo();
		newWxTextPo.setTtGreet(greet);
		newWxTextPo.setTtAnswer(answer);
		newWxTextPo.setCreateDate(new Date());
		newWxTextPo.setMarkForDelete(false);
		newWxTextPo.setCreateBy(1L);
		int insert = 0;
		try {
			insert = wxTextDao.insert(newWxTextPo);
		} catch (Exception e) {
			LOG.info("wxText保存失败"+e);
			e.printStackTrace();
		}
		return insert;
	}

	

}
